import rclpy
import cv2
import cv_bridge
from rclpy.node import Node
from sensor_msgs.msg import Image

class MjpegToBgrNode(Node):
    def __init__(self):
        super().__init__('trans')
        self.get_logger().info("start trans")
        self.bridge = cv_bridge.CvBridge()
        self.image_sub = self.create_subscription(Image, 'image', self.image_callback, 10)
        self.pub = self.create_publisher(Image, '/image_trans', 10)
    
    def image_callback(self, msg):
        self.get_logger().info("callback is running")
        try:
            # Convert ROS Image message to OpenCV image
            image = self.bridge.compressed_imgmsg_to_cv2(msg, 'bgr8')
            # Resize image to 60x60
            new_size = (120, 120)
            image_new = cv2.resize(image, dsize=new_size)
            # Convert OpenCV image back to ROS Image message
            bgr_msg = self.bridge.cv2_to_imgmsg(image_new, 'bgr8')
            # Publish the resized image
            self.pub.publish(bgr_msg)
        except cv_bridge.CvBridgeError as e:
            self.get_logger().error(f"Publish CvBridge Error: {e}")
            
def main(args=None):
    rclpy.init(args=args)
    transform = MjpegToBgrNode()
    rclpy.spin(transform)
    transform.destroy_node()
    rclpy.shutdown()

if __name__ == '__main__':
    main()
